package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessCart;
import com.digitalchina.lxnsy.api.BusinessFarmSystem;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.AddressVO;
import com.digitalchina.lxnsy.entity.CartVO;
import com.digitalchina.lxnsy.entity.GenerateOrderVO;
import com.digitalchina.lxnsy.entity.OrderItemVO;
import com.digitalchina.lxnsy.entity.OrderVO;
import com.digitalchina.lxnsy.entity.PayVO;
import com.digitalchina.lxnsy.entity.PostageVO;
import com.digitalchina.lxnsy.entity.ProductInfoVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.MathExtend;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.wxapi.WXPayEntryActivity;
import com.digitalchina.lxnsy.xml.PersonalInfoXML;
import com.digitalchina.lxnsy.xml.UserXML;
import com.facebook.drawee.view.SimpleDraweeView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/8/2 16:33
 * 修改备注：
 * ================================================
 */
public class SubmitOrderActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.tv_submit_order_post)
    TextView tvSubmitOrderPost; //邮寄
    @Bind(R.id.tv_submit_order_take_their)
    TextView tvSubmitOrderTakeTheir; //自提
    @Bind(R.id.tv_submit_order_address_type)
    TextView tvSubmitOrderAddressType; //自提地址/邮寄地址
    @Bind(R.id.tv_submit_order_person_name)
    TextView tvSubmitOrderPersonName; //邮寄 收货人姓名
    @Bind(R.id.tv_submit_order_person_mobile)
    TextView tvSubmitOrderPersonMobile; // 邮寄 收货人手机号
    @Bind(R.id.ll_submit_order_person_info)
    LinearLayout llSubmitOrderPersonInfo; // 邮寄 收货人信息
    @Bind(R.id.tv_submit_order_show_address)
    TextView tvSubmitOrderShowAddress; // 邮寄/自提地址
    @Bind(R.id.iv_submit_order_farm_logo)
    SimpleDraweeView ivSubmitOrderFarmLogo; //农庄Logo
    @Bind(R.id.tv_submit_order_farm_name)
    TextView tvSubmitOrderFarmName; //农庄名称
    @Bind(R.id.tv_submit_order_farm_contact)
    TextView tvSubmitOrderFarmContact; //农庄联系方式
    @Bind(R.id.iv_submit_order_goods_image)
    SimpleDraweeView ivSubmitOrderGoodsImage; //商品图片
    @Bind(R.id.tv_submit_order_goods_description)
    TextView tvSubmitOrderGoodsDescription; //商品描述
    @Bind(R.id.tv_submit_order_goods_price)
    TextView tvSubmitOrderGoodsPrice; //商品价格
    @Bind(R.id.tv_submit_order_goods_num)
    TextView tvSubmitOrderGoodsNum; // 商品数量
    @Bind(R.id.iv_submit_order_add)
    ImageView ivSubmitOrderAdd; //增加数量按钮
    @Bind(R.id.tv_submit_order_number)
    TextView tvSubmitOrderNumber; //数量
    @Bind(R.id.iv_submit_order_subtract)
    ImageView ivSubmitOrderSubtract; //减少数量按钮
    @Bind(R.id.tv_submit_order_goods_total_price)
    TextView tvSubmitOrderGoodsTotalPrice; //商品总价
    @Bind(R.id.tv_submit_order_goods_total_price_tag)
    TextView tvSubmitOrderGoodsTotalPriceTag;
    @Bind(R.id.tv_submit_order_total_goods_num)
    TextView tvSubmitOrderTotalGoodsNum; //购买数量
    @Bind(R.id.tv_submit_order_real_payment)
    TextView tvSubmitOrderRealPayment; //实付金额
    @Bind(R.id.btn_submit_order)
    Button btnSubmitOrder; //提交订单按钮
    @Bind(R.id.ll_submit_order_address)
    LinearLayout llSubmitOrderAddress; //订单地址
    @Bind(R.id.tv_submit_order_pay_way)
    TextView tvSubmitOrderPayWay; //支付方式
    @Bind(R.id.ll_submit_order_address_layout)
    LinearLayout llSubmitOrderAddressLayout;//提交订单地址布局
    @Bind(R.id.tv_submit_order_service_date)
    TextView tvSubmitOrderServiceDate;//特色服务时间
    @Bind(R.id.rl_submit_order_choose_service_date_layout)
    RelativeLayout rlSubmitOrderChooseServiceDateLayout;//特色服务日期选择布局
    @Bind(R.id.ll_submit_order_choose_date)
    LinearLayout llSubmitOrderChooseDate;//特色服务时间选择按钮
    @Bind(R.id.tv_submit_order_choose_address_hint)
    TextView tvSubmitOrderChooseAddressHint;
    @Bind(R.id.iv_submit_order_right_arrow)
    ImageView ivSubmitOrderRightArrow;
    @Bind(R.id.tv_submit_order_postage)
    TextView tvSubmitOrderPostage;//邮费
    @Bind(R.id.rl_submit_order_goods_item)
    RelativeLayout rlSubmitOrderGoodsItem;//默认商品布局
    @Bind(R.id.ll_item_goods_layout)
    LinearLayout llItemGoodsLayout;//动态加载商品布局
    @Bind(R.id.ll_submit_order_buy_num_layout)
    RelativeLayout rlSubmitOrderBuyNumLayout;
    @Bind(R.id.tv_submit_order_goods_attrName)
    TextView tvSubOrderGoodsAttrName;// 产品属性名称

//    @Bind(R.id.ll_item_goods_layout)
//    LinearLayout llItemGoodsLayout;//动态商品布局
//    @Bind(R.id.item_goods_iv_picture)
//    SimpleDraweeView itemGoodsIvPicture;// 商品图片
//    @Bind(R.id.item_goods_tv_name)
//    TextView itemGoodsTvName; // 商品名称
//    @Bind(R.id.item_goods_tv_price)
//    TextView itemGoodsTvPrice; // 商品价格
//    @Bind(R.id.item_goods_tv_num)
//    TextView itemGoodsTvNum; // 商品数量

    //农特产品
    private List<ProductInfoVO> listProductVO = new ArrayList<>();
    private ProductInfoVO productVO;
    private List<OrderItemVO> orderItemVOList = new ArrayList<>();
    private OrderItemVO orderItemVOs; //订单项
    private int num; //购买数量
    private String productId;//商品ID
    private List<OrderVO> orderVOList = new ArrayList<>();
    private OrderVO orderVO;//订单信息
    private Calendar calendar = Calendar.getInstance();

    private int cartDeliveryMode;//购物车提货模式

    private AddressVO addressVO;//邮寄地址信息
    private String goodsPrice;//商品价格

    private BigDecimal postPrice = new BigDecimal("0.00");//邮费


    private boolean isPostFree = false;//是否免邮

    private String defAddress;//默认地址

    private String chooseDate;//预计服务时间

    private List<AddressVO> mAddressList;

    private int msgWhat;

    private boolean isTakeBtnChecked, isPostBtnChecked;

    //购物车
    private List<CartVO> cartVOList = new ArrayList<>();
    private List<CartVO.ShoppingCartItemVOListBean> shoppingCartItemVOList = new ArrayList<>();

    //产品属性对话框
    private HashMap<String, Object> propertyData = new HashMap<>();
    private ProductInfoVO.AgricultureProductPriceListBean selectVO;

//    //服务属性对话框
//    private HashMap<String, Object> servicePropertyData = new HashMap<>();
//    private ServiceVO.AgricultureProductPriceListBean serviceProperty;

    private String selectName;// 选中的产品属性价格和名称


    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_submit_order);
        setTitle("确认订单");
//        View itemGoods = LayoutInflater.from(this).inflate(R.layout.item_goods, null);
//        llItemGoodsLayout.addView(itemGoods);
    }

    @Override
    public void initMember() {

        // 获取地址列表
        BusinessFarmSystem.getAddressList(this, mHandler);

        if (getIntent().hasExtra("productVO")) {//农特产品详情

            rlSubmitOrderGoodsItem.setVisibility(View.VISIBLE);

            productVO = (ProductInfoVO) getIntent().getSerializableExtra("productVO");
            productId = productVO.getId();
            goodsPrice = productVO.getPrice();

            // 邮费 isFreePostage = 1 为包邮
            if (productVO.getIsFreePostage().equals("1")) {
                isPostFree = true;
                postPrice = new BigDecimal("0.00");
            } else {
                isPostFree = false;
                postPrice = new BigDecimal(productVO.getPostage());
            }

            num = productVO.getBuyNumber();

            PostageVO postageVO = new PostageVO();
            postageVO.setProductId(productId);
            postageVO.setNum(num);
            List<PostageVO> list = new ArrayList<>();
            list.add(postageVO);
            computePostAge(list);

            TakeTheirOrPostAddress("post");
            tvSubmitOrderTakeTheir.setEnabled(false);
            tvSubmitOrderAddressType.setText("收货地址");


            initProductData(defAddress,
                    productVO.getFarmInfo().getLogo(),
                    productVO.getFarmInfo().getName(),
                    productVO.getFarmInfo().getContactNumber(),
                    productVO.getProductImageList().size() >= 1 ? productVO.getProductImageList().get(0).getImage() : "",//农产品图片
                    productVO.getName(),
                    String.valueOf(goodsPrice),
                    String.valueOf(num),
                    String.valueOf(num),
                    String.valueOf(num),
                    String.valueOf(new BigDecimal(MathExtend.multiply(goodsPrice, String.valueOf(num))).setScale(2, BigDecimal.ROUND_HALF_UP)),
                    "线下支付");

        } else if (getIntent().hasExtra("propertyData")) {// 来自产品属性弹出框
            rlSubmitOrderGoodsItem.setVisibility(View.VISIBLE);

            propertyData = (HashMap<String, Object>) getIntent().getSerializableExtra("propertyData");
            productVO = (ProductInfoVO) propertyData.get("productVO");
            selectVO = (ProductInfoVO.AgricultureProductPriceListBean) propertyData.get("selectVO");// 属性VO

            goodsPrice = (String) propertyData.get("selectPrice");// 属性价格
            selectName = (String) propertyData.get("selectName");// 属性名称


            productId = productVO.getId();

            // 邮费 isFreePostage = 1 为包邮
            if (productVO.getIsFreePostage().equals("1")) {
                isPostFree = true;
                postPrice = new BigDecimal("0.00");
            } else {
                isPostFree = false;
                postPrice = new BigDecimal(productVO.getPostage());
            }

            num = productVO.getBuyNumber();

            PostageVO postageVO = new PostageVO();
            postageVO.setProductId(productId);
            postageVO.setNum(num);
            List<PostageVO> list = new ArrayList<>();
            list.add(postageVO);
            computePostAge(list);

            TakeTheirOrPostAddress("post");
            tvSubmitOrderTakeTheir.setEnabled(false);
            tvSubmitOrderAddressType.setText("收货地址");


            initProductData(defAddress,
                    productVO.getFarmInfo().getLogo(),
                    productVO.getFarmInfo().getName(),
                    productVO.getFarmInfo().getContactNumber(),
                    productVO.getProductImageList().size() >= 1 ? productVO.getProductImageList().get(0).getImage() : "",//农产品图片
                    productVO.getName(),
                    String.valueOf(goodsPrice),
                    String.valueOf(num),
                    String.valueOf(num),
                    String.valueOf(num),
                    String.valueOf(new BigDecimal(MathExtend.multiply(goodsPrice, String.valueOf(num))).setScale(2, BigDecimal.ROUND_HALF_UP)),
                    "线下支付");
        } else if (getIntent().hasExtra("cartList")) {//购物车
            cartVOList = (List<CartVO>) getIntent().getSerializableExtra("cartList");
            LogUtils.e(cartVOList);
            for (int i = 0; i < cartVOList.get(0).getShoppingCartItemVOList().size(); i++) {
                if (cartVOList.get(0).getShoppingCartItemVOList().get(i).isCheck()) {
                    shoppingCartItemVOList.add(cartVOList.get(0).getShoppingCartItemVOList().get(i));
                }
            }

            initCartData();//购物车
        }

    }

    /**
     * 初始来自购物车数据
     */
    private void initCartData() {
        cartDeliveryMode = Integer.parseInt(getDeliveryType()); // 0代表都支持  1代表只支持邮递  2代表只支持自提

        cartAddressChoose("post");
        tvSubmitOrderTakeTheir.setEnabled(false);
        tvSubmitOrderAddressType.setText("收货地址");


        llSubmitOrderAddressLayout.setVisibility(View.VISIBLE);//配送地址布局

        rlSubmitOrderChooseServiceDateLayout.setVisibility(View.GONE);//预计前往时间（服务）布局

        rlSubmitOrderBuyNumLayout.setVisibility(View.GONE);//购买数量加减布局

        tvSubmitOrderShowAddress.setText(defAddress);

        FrescoUtil.showImageSmall(cartVOList.get(0).getSupplierLogo(), ivSubmitOrderFarmLogo);

        tvSubmitOrderFarmName.setText(cartVOList.get(0).getSupplierName());

        tvSubmitOrderFarmContact.setText(cartVOList.get(0).getSupplierNumber());//TODO 获取真实数据

        tvSubmitOrderTotalGoodsNum.setText(String.format("共%s件商品", shoppingCartItemVOList.size()));

        tvSubmitOrderGoodsTotalPriceTag.setText("小计 ￥");

        tvSubmitOrderGoodsTotalPrice.setText(String.format("%s", new BigDecimal(getCartTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP)));

        tvSubmitOrderRealPayment.setText(String.format("实付款￥ %s", new BigDecimal(getCartTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP)));//TODO 邮寄需要加上邮费

        initGoodsView();

    }

    /**
     * 根据商品数量 动态加载布局
     */
    private void initGoodsView() {
        llItemGoodsLayout.removeAllViews();

//        List<PostageVO> list = new ArrayList<>();//运费集合

        int goodsListSize = shoppingCartItemVOList.size();
//        if (1 == delivertype) {//邮寄
        for (int i = 0; i < goodsListSize; i++) {

            View goodsLayout = LayoutInflater.from(this).inflate(R.layout.item_goods, null);

            SimpleDraweeView goodsPic = (SimpleDraweeView) goodsLayout.findViewById(R.id.item_goods_iv_picture);
            TextView goodsName = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_name);
            TextView goodsPrice = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_price);
            TextView goodsNum = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_num);
            TextView attrName = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_attrName);

            attrName.setText(shoppingCartItemVOList.get(i).getAttrName() != null ? shoppingCartItemVOList.get(i).getAttrName() : "");
            goodsName.setText(shoppingCartItemVOList.get(i).getItemName());
            FrescoUtil.showImageSmall(shoppingCartItemVOList.get(i).getItemLogo(), goodsPic);
            goodsPrice.setText(String.format("￥ %s", shoppingCartItemVOList.get(i).getItemPrice()));
            goodsNum.setText(String.format("x %s", shoppingCartItemVOList.get(i).getItemQuantity()));

            llItemGoodsLayout.addView(goodsLayout);

//                PostageVO postageVO = new PostageVO();
//                postageVO.setNum(Integer.parseInt(shoppingCartItemVOList.get(i).getItemQuantity()));
//                postageVO.setProductId(shoppingCartItemVOList.get(i).getItemId());
//
//                list.add(postageVO);
        }
//            computePostAge(list);
//        }
//        else {
//            for (int i = 0; i < goodsListSize; i++) {
//
//                View goodsLayout = LayoutInflater.from(this).inflate(R.layout.item_goods, null);
//
//                SimpleDraweeView goodsPic = (SimpleDraweeView) goodsLayout.findViewById(R.id.item_goods_iv_picture);
//                TextView goodsName = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_name);
//                TextView goodsPrice = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_price);
//                TextView goodsNum = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_num);
//                TextView attrName = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_attrName);
//
//                attrName.setText(shoppingCartItemVOList.get(i).getAttrName() != null ? shoppingCartItemVOList.get(i).getAttrName() : "");
//                goodsName.setText(shoppingCartItemVOList.get(i).getItemName());
//                FrescoUtil.showImageSmall(shoppingCartItemVOList.get(i).getItemLogo(), goodsPic);
//                goodsPrice.setText(String.format("￥ %s", shoppingCartItemVOList.get(i).getItemPrice()));
//                goodsNum.setText(String.format("x %s", shoppingCartItemVOList.get(i).getItemQuantity()));
//
//                llItemGoodsLayout.addView(goodsLayout);
//            }
//        }
    }

    /**
     * 获取来自购物车的商品总价
     *
     * @return
     */
    private String getCartTotalPrice() {
        double total = 0;
        for (int i = 0; i < shoppingCartItemVOList.size(); i++) {
            total += new BigDecimal(MathExtend.multiply(shoppingCartItemVOList.get(i).getItemPrice(), shoppingCartItemVOList.get(i).getItemQuantity())).doubleValue();
        }
        return String.valueOf(total);
    }

    /**
     * 获取来自购物车的商品总价
     *
     * @return 0代表都支持  1代表只支持邮递  2代表只支持自提
     */

    private String getDeliveryType() {

        for (int i = 0; i < shoppingCartItemVOList.size(); i++) {
            // 如果有一个是自提  直接返回只能自提
            if ("0".equals(shoppingCartItemVOList.get(i).getHasPostMethod()) && "1".equals(shoppingCartItemVOList.get(i).getHasTakenMethod()))
                return "2";
        }

        for (int i = 0; i < shoppingCartItemVOList.size(); i++) {
            // 如果有一个是邮寄  直接返回只能邮寄
            if ("1".equals(shoppingCartItemVOList.get(i).getHasPostMethod()) && "0".equals(shoppingCartItemVOList.get(i).getHasTakenMethod()))
                return "1";
        }

        return "0";
    }


    /**
     * 获取购物车快递费用
     */
    private void getCartPostAge() {
        List<PostageVO> list = new ArrayList<>();//运费集合
        int goodsListSize = shoppingCartItemVOList.size();
//        if (goodsListSize == 1) {

        for (int i = 0; i < goodsListSize; i++) {
            PostageVO postageVO = new PostageVO();
            postageVO.setNum(Integer.parseInt(shoppingCartItemVOList.get(i).getItemQuantity()));
            postageVO.setProductId(shoppingCartItemVOList.get(i).getItemId());

            list.add(postageVO);
        }
//        }
//        else {
//            List<String> idList = new ArrayList<>();
//            for (int i = 0; i < goodsListSize; i++) {
//
//                if (idList.size() > 0) {
//
//                    if (idList.contains(shoppingCartItemVOList.get(i).getItemId())) {
//
//                        for (int j = 0; j < idList.size(); j++) {
//                            if (shoppingCartItemVOList.get(i).getItemId().equals(idList.get(j))) {
//                                list.get(j).setNum(list.get(j).getNum() + Integer.parseInt(shoppingCartItemVOList.get(i).getItemQuantity()));
//                            }
//                        }
//
//                    } else {
//                        PostageVO postageVO = new PostageVO();
//                        postageVO.setNum(Integer.parseInt(shoppingCartItemVOList.get(i).getItemQuantity()));
//                        postageVO.setProductId(shoppingCartItemVOList.get(i).getItemId());
//                        list.add(postageVO);
//                        idList.add(shoppingCartItemVOList.get(i).getItemId());
//                    }
//                } else {
//
//                    PostageVO postageVO = new PostageVO();
//                    postageVO.setNum(Integer.parseInt(shoppingCartItemVOList.get(i).getItemQuantity()));
//                    postageVO.setProductId(shoppingCartItemVOList.get(i).getItemId());
//                    list.add(postageVO);
//                    idList.add(shoppingCartItemVOList.get(i).getItemId());
//                }
//
//            }
//        }
        computePostAge(list);
    }

    /**
     * 初始化产品数据
     *
     * @param address          自提/邮寄地址
     * @param farmLogo         农庄Logo
     * @param farmName         农庄名称
     * @param farmContact      农庄联系方式
     * @param goodsImage       商品图片
     * @param goodsDescription 商品描述
     * @param goodsPrice       商品价格
     * @param goodsNum         商品数量
     * @param buyNum           购买数量
     * @param totalGoodsNum    总购买商品数
     * @param totalPrice       商品总价
     * @param payWay           支付方式
     */

    //初始化农产品订单
    private void initProductData(String address, String farmLogo, String farmName, String farmContact,
                                 String goodsImage, String goodsDescription, String goodsPrice, String goodsNum,
                                 String buyNum, String totalGoodsNum, String totalPrice, String payWay) {

        if (getIntent().hasExtra("propertyData"))//来自产品属性对话框
            tvSubOrderGoodsAttrName.setText(selectName);// 产品属性名称


        llSubmitOrderAddressLayout.setVisibility(View.VISIBLE);//配送地址

        rlSubmitOrderChooseServiceDateLayout.setVisibility(View.GONE);//预计前往时间（服务）

        tvSubmitOrderShowAddress.setText(address);

        FrescoUtil.showImageSmall(farmLogo, ivSubmitOrderFarmLogo);

        tvSubmitOrderFarmName.setText(farmName);

        tvSubmitOrderFarmContact.setText(farmContact);

        FrescoUtil.showImageSmall(goodsImage, ivSubmitOrderGoodsImage);

        tvSubmitOrderGoodsDescription.setText(goodsDescription);

        tvSubmitOrderGoodsPrice.setText(String.format("￥ %s", goodsPrice));

        tvSubmitOrderGoodsNum.setText(String.format("× %s", goodsNum));

        tvSubmitOrderNumber.setText(buyNum);

        tvSubmitOrderTotalGoodsNum.setText(String.format("共%s件商品", totalGoodsNum));

        tvSubmitOrderGoodsTotalPriceTag.setText("小计 ￥");

        tvSubmitOrderGoodsTotalPrice.setText(String.format("%s", totalPrice));

        tvSubmitOrderPayWay.setText(payWay);

        tvSubmitOrderRealPayment.setText(String.format("实付款￥ %s", totalPrice));
    }

    //初始化特色服务订单数据
    private void initServiceData(String farmLogo, String farmName, String farmContact,
                                 String goodsImage, String goodsDescription, String goodsPrice, String goodsNum,
                                 String buyNum, String totalGoodsNum, String totalPrice, String payWay) {

        llSubmitOrderAddressLayout.setVisibility(View.GONE);//配送地址

        rlSubmitOrderChooseServiceDateLayout.setVisibility(View.GONE);//预计前往时间（服务）

        FrescoUtil.showImageSmall(farmLogo, ivSubmitOrderFarmLogo);

        tvSubmitOrderFarmName.setText(farmName);

        tvSubmitOrderFarmContact.setText(farmContact);

        FrescoUtil.showImageSmall(goodsImage, ivSubmitOrderGoodsImage);

        tvSubmitOrderGoodsDescription.setText(goodsDescription);

        if (getIntent().hasExtra("serviceProperty"))//来自服务属性对话框
            tvSubOrderGoodsAttrName.setText(selectName);// 服务属性名称

        tvSubmitOrderGoodsPrice.setText(String.format("￥ %s", goodsPrice));

        tvSubmitOrderGoodsNum.setText(String.format("× %s", goodsNum));

        tvSubmitOrderNumber.setText(buyNum);

        tvSubmitOrderTotalGoodsNum.setText(String.format("共%s个服务", totalGoodsNum));

        tvSubmitOrderGoodsTotalPriceTag.setText("小计 ￥");

        tvSubmitOrderGoodsTotalPrice.setText(String.format("%s", totalPrice));

        tvSubmitOrderPayWay.setText(payWay);

        tvSubmitOrderRealPayment.setText(String.format("实付款￥ %s", totalPrice));

        tvSubmitOrderServiceDate.setText(String.format("%s/%s/%s", calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)));
    }


    //预售图片显示
    private void insertImage(String goodsDescription) {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.submit_order_before_sale);
        ImageSpan imgSpan = new ImageSpan(this, bitmap);
        SpannableString spanString = new SpannableString("icon");
        spanString.setSpan(imgSpan, 0, "icon".length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvSubmitOrderGoodsDescription.setText(spanString);
        tvSubmitOrderGoodsDescription.append("\t");
        tvSubmitOrderGoodsDescription.append(goodsDescription);
    }

    @Override
    public void addListener() {

        tvSubmitOrderTakeTheir.setOnClickListener(this);
        tvSubmitOrderPost.setOnClickListener(this);
        llSubmitOrderAddress.setOnClickListener(this);
        ivSubmitOrderAdd.setOnClickListener(this);
        ivSubmitOrderSubtract.setOnClickListener(this);
        // 地址监听
        llSubmitOrderAddressLayout.setOnClickListener(this);

        llSubmitOrderAddress.setOnClickListener(this);

//        ivSubmitOrderChooseDate.setOnClickListener(this);

        llSubmitOrderChooseDate.setOnClickListener(this);

        btnSubmitOrder.setOnClickListener(this);

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                msgWhat = msg.what;
                switch (msg.what) {
                    case MSG.MSG_ADDRESS_LIST_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_ADDRESS_LIST_FIELD:
                        showToast(msg.obj.toString());
                        break;
//                    case MSG.MSG_BOOK_ORDER_SUCCESS://预定订单
//                        dismissDialog();
//                        callBack(msg.obj);
//                        break;
//                    case MSG.MSG_BOOK_ORDER_FIELD:
//                        dismissDialog();
//                        showToast(msg.obj.toString());
//                        break;
                    case MSG.MSG_GENERATE_ORDERS_SUCCESS://购买订单
                        dismissDialog();
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GENERATE_ORDERS_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString());
                        break;
//                    case MSG.MSG_SELECT_ORDER_OVER://我知道了（弹出框）
//                        finish();
//                        break;
//                    case MSG.MSG_REMOVE_SHOPPING_BYORDERNOS_SUCCESS://删除指定的商品（订单结算时的回调）
//                        LogUtils.e(msg.obj.toString());
//                        //TODO 移除购物车商品成功
//                        break;
//                    case MSG.MSG_REMOVE_SHOPPING_BYORDERNOS_FIELD:
//                        //TODO 移除购物车商品失败
//                        LogUtils.e(msg.obj.toString());
//                        break;
                    case MSG.MSG_COMPUTE_POSTAGE_FOR_PRODUCT_JSON_SUCCESS://快递用费计算
                        callBack(msg.obj);
                        break;
//                    case MSG.MSG_COMPUTE_POSTAGE_FOR_PRODUCT_JSON_FIELD:
//                        //快递费用返回失败
//                        dismissDialog();
//                        showToast(msg.obj.toString());
//                        break;
                    case MSG.MSG_GET_PRODUCT_INFO_SUCCESS:// 农特产品详情
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_PRODUCT_INFO_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString()); //TODO 农特产品详情失败
                        break;
//                    case MSG.MSG_GET_SPECIAL_SERVICE_DETAIL_SUCCESS:
//                        callBack(msg.obj);
//                        break;
//                    case MSG.MSG_GET_SPECIAL_SERVICE_DETAIL_FIELD:
//                        dismissDialog();
//                        showToast(msg.obj.toString()); // TODO 获取特色服务详情失败
//                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        switch (msgWhat) {
            case MSG.MSG_ADDRESS_LIST_SUCCESS:
                mAddressList = FastJsonUtil.getListBean(object.toString(), "body", "addressList", AddressVO.class);

                if (mAddressList != null && mAddressList.size() > 0) {
                    llSubmitOrderPersonInfo.setVisibility(View.VISIBLE);
                    addressVO = mAddressList.get(0);
                    tvSubmitOrderPersonName.setText(addressVO.getUserName());
                    tvSubmitOrderPersonMobile.setText(addressVO.getMobilePhone());
                    displayAddress(addressVO, tvSubmitOrderShowAddress);
                } else {
                    tvSubmitOrderShowAddress.setText("请选择收货地址");
                }
                break;
            case MSG.MSG_GENERATE_ORDERS_SUCCESS://购买订单
                List<String> orderNoList = FastJsonUtil.getListBean(object.toString(), "body", "orderNoList", String.class);
                String orderNo = orderNoList != null ? orderNoList.get(0) : "";

                if (getIntent().hasExtra("cartList")) {// 来自购物车
                    BusinessCart.removeShoppingByOrderNos(this, orderNo, mHandler);//TODO 多商家的话需要修改
                }
                PayVO payVO = new PayVO();
                payVO.setPrice(orderVO.getTotalPriceReal());
                payVO.setOrderNO(orderNo);
                payVO.setType(1);
                GotoUtil.gotoActivity(SubmitOrderActivity.this, WXPayEntryActivity.class, true, "payVO", payVO);
                break;
            case MSG.MSG_COMPUTE_POSTAGE_FOR_PRODUCT_JSON_SUCCESS://快递用费计算

                String price = FastJsonUtil.getString(object.toString(), "data");
                postPrice = new BigDecimal(price);
                if (getIntent().hasExtra("cartList")) {
                    tvSubmitOrderPostage.setText(String.format("运费%s元", postPrice.setScale(2, BigDecimal.ROUND_HALF_UP)));
                    tvSubmitOrderPostage.setVisibility(View.VISIBLE);
                    tvSubmitOrderRealPayment.setText(String.format("实付款￥ %s", new BigDecimal(MathExtend.add(getCartTotalPrice(), String.valueOf(postPrice))).setScale(2, BigDecimal.ROUND_HALF_UP)));//TODO 获取真实数据
                } else
                    setNumAndPrice(num);
                break;
            case MSG.MSG_GET_PRODUCT_INFO_SUCCESS:
                ProductInfoVO productVo = FastJsonUtil.getBean(object.toString(), "body", "productInfo", ProductInfoVO.class);
                if (0 == productVo.getStatus()) {
                    showToast("该农产品已下架");
                    return;
                }
                submitOrder(productVo);
                break;
//            case MSG.MSG_GET_SPECIAL_SERVICE_DETAIL_SUCCESS:
//                ServiceVO serviceVO = FastJsonUtil.getBean(object.toString(), "body", "farmSpecialService", ServiceVO.class);
//                if (0 == serviceVO.getStatus()) {
//                    showToast("该服务已下架");
//                    return;
//                } else {
//                    submitServiceOrder();
//                }
//                break;
        }


    }

    @Override
    public void rightOnClick() {

    }

    String provinceName, cityName, countyName, detailsName, proCode, cityCode;

    /**
     * 地址展示
     */
    private void displayAddress(AddressVO data, TextView tvAddress) {


        if (null == data.getProvince()) {
            provinceName = "";
        } else {
            proCode = data.getProvince().getCode();
            provinceName = data.getProvince().getProvinceName();
        }

        if (null == data.getCity()) {
            cityName = "";
        } else {
            cityCode = data.getCity().getCode();
            cityName = data.getCity().getCityName();
        }

        if (null == data.getCounty())
            countyName = "";
        else
            countyName = data.getCounty().getCountyName();

        if (null == data.getAddress())
            detailsName = "";
        else
            detailsName = data.getAddress();

//        if (!StringUtil.isStrEmpty(proCode) && !StringUtil.isStrEmpty(cityCode)) {
        if (proCode.equals("110000") || proCode.equals("120000") || proCode.equals("310000") || proCode.equals("500000") || (proCode.equals("460000") && cityCode.equals("469000")))
            tvAddress.setText(String.format("%s %s %s", provinceName, countyName, detailsName));
        else
            tvAddress.setText(String.format("%s %s %s %s", provinceName, cityName, countyName, detailsName));
//        }

    }


    @Override
    public void onClick(View v) {
        PostageVO postageVO = new PostageVO();
        List<PostageVO> list = new ArrayList<>();
        switch (v.getId()) {

            case R.id.tv_submit_order_take_their:
                if (isTakeBtnChecked)
                    return;

                if (getIntent().hasExtra("cartList"))
                    cartAddressChoose("take");
                else
                    TakeTheirOrPostAddress("take"); //地址显示(自提)


                break;
            case R.id.tv_submit_order_post:

                if (isPostBtnChecked)
                    return;

                if (getIntent().hasExtra("cartList"))
                    cartAddressChoose("post");
                else
                    TakeTheirOrPostAddress("post"); //地址显示(邮寄)

                break;
            case R.id.iv_submit_order_add://购买数量+

                num += 1;

                setNumAndPrice(num);

                if (isPostFree)  // 包邮则不需要调用邮费接口
                    return;
                postageVO.setProductId(productId);
                postageVO.setNum(num);


                list.add(postageVO);

                computePostAge(list);


                break;
            case R.id.iv_submit_order_subtract://购买数量-

                if (num > 1)
                    num -= 1;
                else
                    return;

                setNumAndPrice(num);

                if (isPostFree) // 包邮则不需要调用邮费接口
                    return;
                postageVO.setProductId(productId);
                postageVO.setNum(num);

                list.add(postageVO);

                computePostAge(list);

                break;
            case R.id.ll_submit_order_choose_date://特色服务日期选择
//                initDate();
                break;

            case R.id.ll_submit_order_address://收货地址选择
                GotoUtil.gotoForResultActivity(SubmitOrderActivity.this, MyAddressListActivity.class, 99, "isShowCheck", true);
                break;

            case R.id.btn_submit_order: //提交订单

                if (StringUtil.isStrEmpty(tvSubmitOrderPersonMobile.getText().toString())) {

                    showToast("收货地址不能为空");
                    return;
                }

                showDialog("请稍候···");

                if (getIntent().hasExtra("productVO") || getIntent().hasExtra("propertyData")) {//农特产品订单提交
                    // 调用农产品详情接口
                    BusinessFarmSystem.getProductInfo(this, productId, mHandler);

                } else if (getIntent().hasExtra("cartList")) {

                    submitCartOrder();
                }

                break;
        }

    }

    /**
     * 计算快递费用
     *
     * @param voList 运费集合
     */
    private void computePostAge(List<PostageVO> voList) {


        JSONArray jsonArray = new JSONArray();

        for (int i = 0; i < voList.size(); i++) {
            JSONObject jsonObject = (JSONObject) JSON.toJSON(voList.get(i));
            jsonArray.add(jsonObject);
        }

        LogUtils.e(jsonArray.toJSONString());

        BusinessFarmSystem.computePostageForProductJson(SubmitOrderActivity.this, jsonArray.toJSONString(), mHandler);
    }


    /**
     * 农产品订单
     */
    private void submitOrder(ProductInfoVO productVO) {
        if (orderItemVOList != null)//防止订单提交失败 重复添加数据
            orderItemVOList.clear();
        if (orderVOList != null)
            orderVOList.clear();
        //现售
        orderItemVOs = new OrderItemVO();
        orderItemVOs.setProductId(productVO.getId());
        orderItemVOs.setProductType("0");//商品类型
        orderItemVOs.setSn(productVO.getProduct_SN());
        orderItemVOs.setProductName(productVO.getName());
        orderItemVOs.setProductDesc(productVO.getSummary());
        orderItemVOs.setPrice(String.valueOf(new BigDecimal(goodsPrice)));
        orderItemVOs.setTotalPrice(String.valueOf(new BigDecimal(MathExtend.multiply(String.valueOf(num), goodsPrice)).add(postPrice)));
        orderItemVOs.setTotalPriceReal(String.valueOf(new BigDecimal(MathExtend.multiply(String.valueOf(num), goodsPrice)).add(postPrice)));
        orderItemVOs.setProductImg(productVO.getProductImageList().size() >= 1 ? productVO.getProductImageList().get(0).getImage() : "");
        orderItemVOs.setIsGift("false");
        orderItemVOs.setQuantity(String.valueOf(num));
        orderItemVOs.setUnit(productVO.getUnit().getName());
        orderItemVOs.setIsMailFree(String.valueOf(isPostFree));

        if (getIntent().hasExtra("propertyData")) {// 产品属性
            orderItemVOs.setPriceType(productVO.getPriceType());
            orderItemVOs.setPreferentialPrice(String.valueOf(new BigDecimal(goodsPrice)));
            orderItemVOs.setAttrName(selectName);
        }

        orderItemVOs.setFreightPrice(String.valueOf(postPrice));
        orderItemVOs.setFreightPriceReal(String.valueOf(postPrice));

        orderItemVOs.setRetainDays(productVO.getRetentionTime());
        //TODO 动态计算
        orderItemVOs.setWeight("");
        //TODO 拼接地址
        orderItemVOs.setProductUrl(URL.URL_GET_PRODUCT_INFO + "?productId=" + productId);
        // 商品分类
        orderItemVOs.setCommodityType(productVO.getType().getName());
        orderItemVOList.add(orderItemVOs);

        //拆单并生成订单
        orderVO = new OrderVO();
//            orderVO.setPickupAddress(productVO.getFarm().getAddress());//取货地址
        orderVO.setTip("");//买家备注
        orderVO.setPaymentType(Constant.PAYMENT_TYPE_ON_LINE);//支付类型 线下支付，在线支付
        orderVO.setShippingType(Constant.SHIPPING_TYPE_POST); //发货类型：不需发货，自提，邮寄
        orderVO.setTotalPriceOrigin(String.valueOf(new BigDecimal(MathExtend.multiply(String.valueOf(num), goodsPrice)).add(postPrice)));/** 应收总价 */
        orderVO.setTotalPriceReal(String.valueOf(new BigDecimal(MathExtend.multiply(String.valueOf(num), goodsPrice)).add(postPrice)));/** 实收总价 */
        orderVO.setSellerId(productVO.getOrgAccId());//卖家ID
        orderVO.setSellerName(productVO.getFarmInfo().getName());//卖家名称
        orderVO.setSellerPhone(productVO.getFarmInfo().getContactNumber());//卖家电话
        orderVO.setSellerLogo(productVO.getFarmInfo().getLogo());//卖家logo
        orderVO.setSellerAddress(productVO.getFarmInfo().getFullAddress());//卖家地址
        orderVO.setIsInvoice("false");//是否开具发票
        orderVO.setInvoiceTitle("");//发票抬头
        //TODO 预售才有
        orderVO.setAppointShippingAt("");//约定发货（取货）时间

        orderVO.setOrderItemVOList(orderItemVOList);//订单项
        orderVO.setFee(String.valueOf(new BigDecimal(0)));//手续费
        orderVO.setCoupon("");//优惠码
        orderVO.setCouponPrice(String.valueOf(new BigDecimal(0)));//优惠金额
        orderVO.setPaidAmount(String.valueOf(new BigDecimal(0)));//已付金额
        orderVO.setAdjustAmount(String.valueOf(new BigDecimal(0)));//调整金额
        if (isPostFree) {

            //TODO 待确定
            orderVO.setFreightPriceOrigin(String.valueOf(new BigDecimal("0.00")));/** 应收总运费 */
            orderVO.setFreightPriceReal(String.valueOf(new BigDecimal("0.00")));/** 实收总运费 */
//                orderVO.setTotalPriceOrigin(new BigDecimal(num * goodsPrice));/** 应收总价 */
//                orderVO.setTotalPriceReal(new BigDecimal(num * goodsPrice));/** 实收总价 */
        } else {

            //TODO 待确定
//                orderVO.setFreightPriceOrigin(new BigDecimal(productVO.getPostage()));/** 应收总运费 */
//                orderVO.setFreightPriceReal(new BigDecimal(productVO.getPostage()));/** 实收总运费 */
            orderVO.setFreightPriceOrigin(String.valueOf(postPrice));/** 应收总运费 */
            orderVO.setFreightPriceReal(String.valueOf(postPrice));/** 实收总运费 */
//                orderVO.setTotalPriceOrigin(new BigDecimal(num * goodsPrice).add(new BigDecimal(productVO.getPostage())));/** 应收总价 */
//                orderVO.setTotalPriceReal(new BigDecimal(num * goodsPrice).add(new BigDecimal(productVO.getPostage())));/** 实收总价 */
        }

        orderVO.setDeductIntegral(String.valueOf(0));/** 抵扣积分 */
        orderVO.setDeductAmount(String.valueOf(new BigDecimal(0)));/** 抵扣金额 */
        orderVOList.add(orderVO);

        generateOrder();//购买
    }

    /**
     * 购物车订单提交
     */
    private void submitCartOrder() {//TODO 待完善数据

        if (null != orderVOList)
            orderVOList.clear();// 清除数据 防止订单提交失败重复添加数据

        List<OrderItemVO> orderItemVOList = new ArrayList<>();// 订单项


        List<PostageVO> list = new ArrayList<>();

        for (int i = 0; i < shoppingCartItemVOList.size(); i++) {
            OrderItemVO orderItemVO = new OrderItemVO();
            orderItemVO.setProductId(shoppingCartItemVOList.get(i).getItemId());//商品ID
            orderItemVO.setProductType("0");//商品类型
            orderItemVO.setSn("");//编号
            orderItemVO.setProductName(shoppingCartItemVOList.get(i).getItemName());//商品名称
            orderItemVO.setProductDesc("");//商品描述
            orderItemVO.setPrice(String.valueOf(new BigDecimal(shoppingCartItemVOList.get(i).getItemPrice())));//商品价格
            orderItemVO.setTotalPrice(String.valueOf(new BigDecimal(MathExtend.add(MathExtend.multiply(shoppingCartItemVOList.get(i).getItemPrice(), shoppingCartItemVOList.get(i).getItemQuantity()), shoppingCartItemVOList.get(i).getPostage()))));//总价
            orderItemVO.setTotalPriceReal(String.valueOf(new BigDecimal(MathExtend.add(MathExtend.multiply(shoppingCartItemVOList.get(i).getItemPrice(), shoppingCartItemVOList.get(i).getItemQuantity()), shoppingCartItemVOList.get(i).getPostage()))));//实付总价
            orderItemVO.setProductImg(shoppingCartItemVOList.get(i).getItemLogo());//商品图片
            orderItemVO.setAttrName(shoppingCartItemVOList.get(i).getAttrName()); // 商品属性
            orderItemVO.setPreferentialPrice(String.valueOf(new BigDecimal(shoppingCartItemVOList.get(i).getItemPrice())));//TODO 促销价格
            orderItemVO.setPriceType(shoppingCartItemVOList.get(i).getPriceType());//TODO 定价类型 0 固定定价  1 属性定价
            orderItemVO.setIsGift("");//是否赠品
            orderItemVO.setQuantity(String.valueOf(Integer.parseInt(shoppingCartItemVOList.get(i).getItemQuantity())));//数量
            orderItemVO.setUnit(shoppingCartItemVOList.get(i).getItemUnit());//商品单位
            orderItemVO.setIsMailFree("");//是否免运费
            orderItemVO.setFreightPrice(String.valueOf(new BigDecimal(shoppingCartItemVOList.get(i).getPostage())));//运费
            orderItemVO.setFreightPriceReal(String.valueOf(new BigDecimal(shoppingCartItemVOList.get(i).getPostage())));
            orderItemVO.setRetainDays("");//保留天数
            orderItemVO.setWeight("");//重量
            orderItemVO.setProductUrl(URL.URL_GET_PRODUCT_INFO + "?productId=" + shoppingCartItemVOList.get(i).getItemId());//商品链接
//            orderItemVO.setCommodityType();
            orderItemVOList.add(orderItemVO);

            PostageVO postageVO = new PostageVO();
            postageVO.setNum(Integer.parseInt(shoppingCartItemVOList.get(i).getItemQuantity()));
            postageVO.setProductId(shoppingCartItemVOList.get(i).getItemId());

            list.add(postageVO);
        }

        computePostAge(list);

        orderVO = new OrderVO();
        orderVO.setPickupAddress(cartVOList.get(0).getSupplierAddress());//取货地址
        orderVO.setTip("");//买家备注
        orderVO.setPaymentType(Constant.PAYMENT_TYPE_ON_LINE);

        orderVO.setShippingType(Constant.SHIPPING_TYPE_POST);//发货类型：不需发货，自提，邮寄

        //TODO 运费 总金额

        orderVO.setSellerId(cartVOList.get(0).getSupplierId());//卖家
        orderVO.setSellerName(cartVOList.get(0).getSupplierName());//卖家名称
        orderVO.setSellerPhone(cartVOList.get(0).getSupplierNumber());//卖家电话
        orderVO.setSellerLogo(cartVOList.get(0).getSupplierLogo());//卖家logo
        orderVO.setSellerAddress(cartVOList.get(0).getSupplierAddress());//卖家地址
        orderVO.setIsInvoice("");//是否开具发票
        orderVO.setInvoiceTitle("");//发票抬头
        orderVO.setAppointShippingAt("");//约定发货（取货）时间
        orderVO.setOrderItemVOList(orderItemVOList);//订单项
        orderVO.setFee(String.valueOf(new BigDecimal(0)));//手续费
        orderVO.setCoupon("");//优惠码
        orderVO.setCouponPrice(String.valueOf(new BigDecimal(0)));//优惠金额
        orderVO.setPaidAmount(String.valueOf(new BigDecimal(0)));//已付金额
        orderVO.setAdjustAmount(String.valueOf(new BigDecimal(0)));//调整金额
        orderVO.setFreightPriceOrigin(String.valueOf(postPrice));//应收总运费
        orderVO.setFreightPriceReal(String.valueOf(postPrice));//实收总运费
        orderVO.setTotalPriceOrigin(String.valueOf(new BigDecimal(MathExtend.add(getCartTotalPrice(), String.valueOf(postPrice)))));//应收总价
        orderVO.setTotalPriceReal(String.valueOf(new BigDecimal(MathExtend.add(getCartTotalPrice(), String.valueOf(postPrice)))));//实收总价
        orderVO.setDeductIntegral(String.valueOf(0));//抵扣积分
        orderVO.setDeductAmount(String.valueOf(new BigDecimal(0)));//抵扣金额
        orderVOList.add(orderVO);
        generateOrder();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 99 && resultCode == RESULT_OK)
            addressVO = (AddressVO) data.getSerializableExtra("addressVO");

        if (null != addressVO) {
            llSubmitOrderPersonInfo.setVisibility(View.VISIBLE);
            tvSubmitOrderPersonName.setText(addressVO.getUserName());
            tvSubmitOrderPersonMobile.setText(addressVO.getMobilePhone());
            tvSubmitOrderShowAddress.setText(String.format("%s %s %s %s", addressVO.getProvince().getName(),
                    addressVO.getCity() != null ? addressVO.getCity().getName() : "", addressVO.getCounty() != null ? addressVO.getCounty().getName() : "", addressVO.getAddress()));
        } else {
            tvSubmitOrderShowAddress.setText("请选择收货地址");
        }
    }


    /**
     * 非预定订单提交
     */
    private void generateOrder() {

        GenerateOrderVO generateOrderVO = new GenerateOrderVO();
        generateOrderVO.setActivity(this);
        generateOrderVO.setHandler(mHandler);

        generateOrderVO.setBuyerId(UserXML.getUserId(this));
        generateOrderVO.setBuyerLogo(PersonalInfoXML.getHeadportrait(this));


        generateOrderVO.setConsignee(tvSubmitOrderPersonName.getText().toString());
        generateOrderVO.setShippingPhone(tvSubmitOrderPersonMobile.getText().toString());
        generateOrderVO.setShippingAddress(tvSubmitOrderShowAddress.getText().toString().trim());
        generateOrderVO.setPaymentType(Constant.PAYMENT_TYPE_ON_LINE);
        generateOrderVO.setTip("");
        generateOrderVO.setOrderVOList(orderVOList);

        BusinessFarmSystem.generateOrder(generateOrderVO);

    }


    /**
     * 根据商品数量 计算商品总价
     *
     * @param num 购买商品数量
     */
    private void setNumAndPrice(int num) {
        tvSubmitOrderNumber.setText(String.valueOf(num));
        tvSubmitOrderGoodsNum.setText(String.format("× %s", num));
        //TODO 判断商品OR服务 显示不同文字
        if (getIntent().hasExtra("serviceVO")) {
            tvSubmitOrderTotalGoodsNum.setText(String.format("共%s个服务", num));
        } else {
            tvSubmitOrderTotalGoodsNum.setText(String.format("共%s件商品", num));
        }
        tvSubmitOrderGoodsTotalPriceTag.setText("小计 ￥");
        tvSubmitOrderGoodsTotalPrice.setText(String.format("%s", new BigDecimal(MathExtend.multiply(String.valueOf(num), goodsPrice)).setScale(2, BigDecimal.ROUND_HALF_UP)));
        tvSubmitOrderRealPayment.setText(String.format("实付款￥ %s", new BigDecimal(MathExtend.add(MathExtend.multiply(String.valueOf(num), goodsPrice), String.valueOf(postPrice))).setScale(2, BigDecimal.ROUND_HALF_UP)));
        tvSubmitOrderPostage.setVisibility(View.VISIBLE);
        tvSubmitOrderPostage.setText(String.format("运费%s元", postPrice.setScale(2, BigDecimal.ROUND_HALF_UP)));
    }

    /**
     * 自提/邮寄
     *
     * @param receiptType 提货类型
     */
    private void TakeTheirOrPostAddress(String receiptType) {

        isTakeBtnChecked = false;
        isPostBtnChecked = true;


        PostageVO postageVO = new PostageVO();
        postageVO.setProductId(productId);
        postageVO.setNum(num);

        List<PostageVO> list = new ArrayList<>();
        list.add(postageVO);

        computePostAge(list);


        llSubmitOrderAddress.setEnabled(true);
        ivSubmitOrderRightArrow.setVisibility(View.VISIBLE);
        tvSubmitOrderAddressType.setText("收货地址");
        if (null != addressVO) {
            llSubmitOrderPersonInfo.setVisibility(View.VISIBLE);
            tvSubmitOrderPersonName.setText(addressVO.getUserName());
            tvSubmitOrderPersonMobile.setText(addressVO.getMobilePhone());
//                tvSubmitOrderShowAddress.setText(String.format("%s %s %s %s", addressVO.getProvince().getName(),
//                        addressVO.getCity().getName(), addressVO.getCounty().getName(), addressVO.getAddress()));
            displayAddress(addressVO, tvSubmitOrderShowAddress);
        } else {
            tvSubmitOrderShowAddress.setText("请选择收货地址");
        }
        tvSubmitOrderPost.setTextColor(Color.parseColor("#EA595D"));
        tvSubmitOrderPost.setBackgroundResource(R.drawable.submit_order_rectangle_with_radius_select_bg);
        tvSubmitOrderTakeTheir.setTextColor(Color.parseColor("#b3b3b3"));
        tvSubmitOrderTakeTheir.setBackgroundResource(R.drawable.submit_order_rectangle_with_radius_unselect_bg);
    }

    /**
     * 自提/邮寄(来自购物车)
     *
     * @param receiptType 提货类型
     */
    private void cartAddressChoose(String receiptType) {

        isTakeBtnChecked = false;
        isPostBtnChecked = true;


        getCartPostAge();

        llSubmitOrderAddress.setEnabled(true);
        ivSubmitOrderRightArrow.setVisibility(View.VISIBLE);
        tvSubmitOrderAddressType.setText("收货地址");
        if (null != addressVO) {
            llSubmitOrderPersonInfo.setVisibility(View.VISIBLE);
            tvSubmitOrderPersonName.setText(addressVO.getUserName());
            tvSubmitOrderPersonMobile.setText(addressVO.getMobilePhone());
            displayAddress(addressVO, tvSubmitOrderShowAddress);
        } else {
            tvSubmitOrderShowAddress.setText("请选择收货地址");
        }
        tvSubmitOrderPost.setTextColor(Color.parseColor("#EA595D"));
        tvSubmitOrderPost.setBackgroundResource(R.drawable.submit_order_rectangle_with_radius_select_bg);
        tvSubmitOrderTakeTheir.setTextColor(Color.parseColor("#b3b3b3"));
        tvSubmitOrderTakeTheir.setBackgroundResource(R.drawable.submit_order_rectangle_with_radius_unselect_bg);
    }


}
